package com.hmall.order.interceptors;

import com.hmall.order.utlis.OrderHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
 * @Author: Ronin
 * @date 2023/4/8 16:14
 * @Version 2.0
 * @Description: 用户service拦截器,获取请求头中的数据信息
 */
@Component
@Slf4j
public class UserInterceptors implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 1.获取请求头
        String header = request.getHeader("authorization");

        //2.判断请求头数据是否为空
        if (header == null) {
            //没有用户信息
            response.setStatus(403);
            log.warn("用户信息有误,请稍后重试!");
            return false;
        }

        //3.获取当前请求参数
        Long userId = Long.valueOf(header);

        //4.将请求id存入线程数据
        OrderHolder.setUser(userId);

        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //清理当前线程变量
        OrderHolder.remove();
    }
}
